using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WebApi.Core.Interfaces;

namespace WebApi.Controllers
{
    [Authorize]
    [ApiController]
    [Route("api/[controller]")]
    public class FileController : ControllerBase
    {
        private readonly IFileService _fileService;
        private const string ExcelContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        public FileController(IFileService fileService)
        {
            _fileService = fileService;
        }

        [HttpGet("download-excel")]
        public async Task<FileStreamResult> DownloadExcel()
        {
            var stream = await _fileService.GenerateExcelReport();
            return new FileStreamResult(stream, ExcelContentType)
            {
                FileDownloadName = "report.xlsx"
            };
        }

        [HttpGet("download-from-template")]
        public async Task<FileStreamResult> DownloadFromTemplate()
        {
            try
            {
                using  var stream = await _fileService.GenerateFromTemplate("test1.xlsx");
                return new FileStreamResult(stream, ExcelContentType)
                {
                    FileDownloadName = $"report_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                };
            }
            catch (FileNotFoundException)
            {
                throw;
            }
        }

        [HttpPost("upload")]
        public async Task<IActionResult> UploadExcel(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return BadRequest("No file uploaded");

            var result = await _fileService.UploadExcel(file);
            if (result)
            {
                return Ok(new { message = "File uploaded successfully" });
            }
            
            return BadRequest("Failed to upload file");
        }
    }
} 